import os
import tempfile
from loguru import logger
import requests
from django.conf import settings
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from rest_framework import permissions, status
from rest_framework.response import Response
from apps.public import s3
from utils.djSwagger import swagger_view
from .serializers import FileSerializer, ChunkPresignedUrlsSerializer, UploadChunkSerializer, MergeChunkSerializer


@method_decorator(name="post",
                  decorator=swagger_view.swagger_auto_schema(
                      operation_summary="文件上传类接口demo",
                      tags=["File"]))
class UploadFileView(swagger_view.FormView):
    """
    通过表单来配置自定义接口参数
    """
    serializer_class = FileSerializer
    permission_classes = []  # todo:用户权限 403
    authentication_classes = []  # todo:用户认证 401

    def post(self, request, *args, **kwargs):
        return JsonResponse({})


@method_decorator(name="post",
                  decorator=swagger_view.swagger_auto_schema(
                      operation_summary="大文件预签地址",
                      tags=["File"]))
class ChunkPresignedUrlsView(swagger_view.FormView):
    """
    通过表单来配置自定义接口参数
    """
    serializer_class = ChunkPresignedUrlsSerializer
    permission_classes = []  # todo:用户权限 403
    authentication_classes = []  # todo:用户认证 401

    def post(self, request, *args, **kwargs):
        filename = request.data.get("filename")
        key = s3.generate_key(
            directory="demo", filename=filename, is_random=True)
        chunk_count = int(request.data.get("chunk_count"))
        res = s3.get_chunck_presigned_urls(AWS_BUCKET_NAME=settings.AWS_BUCKET_NAME, key=key,
                                           chunk_total=chunk_count)
        res.update({"key": key})
        return JsonResponse(res)


@method_decorator(name="post",
                  decorator=swagger_view.swagger_auto_schema(
                      operation_summary="大文件分片上传",
                      tags=["File"]))
class UploadChunkView(swagger_view.FormView):
    """
    通过表单来配置自定义接口参数
    """
    serializer_class = UploadChunkSerializer
    permission_classes = []  # todo:用户权限 403
    authentication_classes = []  # todo:用户认证 401

    def post(self, request, *args, **kwargs):
        chunk_url = request.data.get("chunk_url")
        file = request.FILES.get("file")
        resp = requests.put(chunk_url, data=file.read())
        return JsonResponse(status=resp.status_code, data={"status": "success"})


@method_decorator(name="post",
                  decorator=swagger_view.swagger_auto_schema(
                      operation_summary="大文件分片合并",
                      tags=["File"]))
class MergeChunkView(swagger_view.FormView):
    """
    通过表单来配置自定义接口参数
    """
    serializer_class = MergeChunkSerializer
    permission_classes = []  # todo:用户权限 403
    authentication_classes = []  # todo:用户认证 401

    def post(self, request, *args, **kwargs):
        key = request.data.get("key")
        UploadId = request.data.get("UploadId")
        resp = s3.merge_ready_chunk(
            settings.AWS_BUCKET_NAME, key=key, UploadId=UploadId)
        url = s3.generate_presigned_url('get_object',
                                        Params={
                                            'Bucket': settings.AWS_BUCKET_NAME, 'Key': key},
                                        ExpiresIn=314496000)
        return JsonResponse(status=200, data={"status": "success", "download_url": url})
